package com.java.demo.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 两个线程输出奇数和偶数
 *
 * @auther zhangwj
 * @date 2020/8/18 2:21 下午
 */
public class Demo5 {

    private static  int a = 1;

    public static void main(String[] args) {
        Demo5 demo5 = new Demo5();
        Lock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        Thread t1 = new Thread(() -> {
            try {
                demo5.add(lock, condition);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t1.setName("11111111");
        Thread t2 = new Thread(() -> {
            try {
                demo5.add(lock, condition);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t2.setName("22222222");
        Thread t3 = new Thread(() -> {
            try {
                demo5.add(lock, condition);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t3.setName("33333333");
        t1.start();
        t2.start();
        t3.start();
    }


    public void add(Lock lock, Condition condition) throws InterruptedException {
        while (a <= 100) {
            lock.lock();
            if (a % 2 > 0) {
                System.out.println(Thread.currentThread().getName() + "---奇数---" + a);
                a++;
                condition.await();
            } else {
                System.out.println(Thread.currentThread().getName() + "---偶数---" + a);
                a++;
                condition.signalAll();
            }
            Thread.sleep(1000);
            lock.unlock();
        }

    }
}
